<script setup lang="ts">
import { theme, Button, Input, Card, Upload, Typography, message, Spin, Select } from 'ant-design-vue'
import { UploadOutlined, SendOutlined, FileTextOutlined, BulbOutlined } from '@ant-design/icons-vue'
import { computed, ref, watch } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { CreateKnowledgeBaseRequest } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores/modules/auth'

// 获取认证store
const authStore = useAuthStore()

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top'
})



const { Title, Text, Paragraph } = Typography
const { token } = theme.useToken()

const styles = computed(() => {
  return {
    'layout': {
      'width': '100%',
      'min-width': '800px',
      'max-width': '1200px',
      'height': '922px',
      'border-radius': `${token.value.borderRadius}px`,
      'display': 'flex',
      'flex-direction': 'column',
      'margin': '0 auto',
      'background': `${token.value.colorBgContainer}`,
      'font-family': `AlibabaPuHuiTi, ${token.value.fontFamily}, sans-serif`,
    },
    'mainArea': {
      'flex': 1,
      'display': 'flex',
      'flex-direction': 'column',
      'height': '100%',
    },
    'contentArea': {
      'flex': 1,
      'padding': '16px',
      'overflow-y': 'auto',
      'background': `${token.value.colorBgContainer}`,
    },
    'welcomeArea': {
      'display': 'flex',
      'flex-direction': 'column',
      'align-items': 'center',
      'justify-content': 'center',
      'height': '100%',
      'text-align': 'center',
    },
    'inputArea': {
      'padding': '16px',
      'border-top': `1px solid ${token.value.colorBorder}`,
      'background': `${token.value.colorBgContainer}`,
    },
  } as const
})

defineOptions({ name: 'ScriptCreation' })

// ==================== State ====================
const currentMode = ref<'welcome' | 'upload' | 'generate' | 'document'>('welcome')
const uploadedFile = ref<File | null>(null)
const fileContent = ref('')
const scriptName = ref('')
const scriptDescription = ref('')
const scriptImage = ref<File | null>(null)
const scriptImageUrl = ref('')
const uploadedFileUrl = ref('')
const aiInput = ref('')
const aiResult = ref('')
const isGenerating = ref(false)
const isProcessingFile = ref(false)
const isSubmitting = ref(false)
const selectedTheme = ref('')
const recommendedThemes = ref([
  { value: 'ancient_palace', label: '古代宫廷中的权力斗争与爱情纠葛' },
  { value: 'modern_spy', label: '现代都市里的商业间谍与背叛' },
  { value: 'victorian_murder', label: '维多利亚时代的神秘庄园谋杀案' },
  { value: 'sci_fi_ai', label: '未来科幻世界的人工智能觉醒' },
  { value: 'republic_shanghai', label: '民国时期的上海滩恩怨情仇' },
  { value: 'medieval_castle', label: '中世纪城堡中的骑士与魔法' },
  { value: 'campus_mystery', label: '现代校园里的青春悬疑故事' },
  { value: 'pirate_treasure', label: '海盗时代的宝藏争夺战' },
  { value: 'zombie_apocalypse', label: '末日丧尸危机中的人性考验' },
  { value: 'space_station', label: '太空站中的神秘失踪事件' }
])

// ==================== File Upload ====================
const handleFileUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    isProcessingFile.value = true

    try {
      const formData = new FormData()
      formData.append('file', file)

      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
      onError?.(error as Error)
    } finally {
      isProcessingFile.value = false
    }
  }
}

const beforeUpload = (file: File) => {
  const allowedTypes = [
    'text/plain',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const allowedExtensions = ['.txt', '.pdf', '.doc', '.docx']

  const isValidType = allowedTypes.includes(file.type) ||
    allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext))

  if (!isValidType) {
    message.error('只能上传 .txt、.pdf、.doc、.docx 格式的文件！')
    return false
  }
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isLt1M) {
    message.error('文件大小不能超过 1MB！')
    return false
  }
  return true
}

const removeFile = () => {
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  fileContent.value = ''
  scriptName.value = ''
  scriptDescription.value = ''
  scriptImage.value = null
  scriptImageUrl.value = ''
  message.info('文件已移除')
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    if (!beforeUpload(file)) return

    isProcessingFile.value = true

    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件选择成功！')
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
    } finally {
      isProcessingFile.value = false
    }
  }
}

const handleFileInputClick = () => {
  const fileInput = document.getElementById('file-input') as HTMLInputElement
  if (fileInput) {
    fileInput.click()
  }
}

// ==================== Image Upload ====================
const handleImageUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        scriptImage.value = file
        scriptImageUrl.value = response.data.data
        message.success('图片上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      message.error('图片上传失败，请重试')
      onError?.(error as Error)
    }
  }
}

const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isLt1M) {
    message.error('图片大小不能超过 1MB！')
    return false
  }
  return true
}

const removeImage = () => {
  scriptImage.value = null
  scriptImageUrl.value = ''
  message.info('图片已移除')
}

// ==================== Form Submit ====================
const handleSubmit = async () => {
  if (!scriptName.value.trim()) {
    message.warning('请输入剧本名称')
    return
  }

  if (!uploadedFileUrl.value) {
    message.warning('请上传剧本文档')
    return
  }

  isSubmitting.value = true
  try {
    // 准备创建知识库的请求数据
    const createKnowledgeBaseData: CreateKnowledgeBaseRequest = {
      fileUrl: uploadedFileUrl.value,
      name: scriptName.value
    }

    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    // 调用创建知识库接口
    const response = await api.createKnowledgeBase(createKnowledgeBaseData, {
      headers
    })

    if (response.data?.code === 0) {
      message.success('剧本知识库创建成功！')
      console.log('知识库创建成功，响应数据:', response.data.data)

      // 重置表单
      backToWelcome()
    } else {
      throw new Error(response.data?.message || '创建失败')
    }
  } catch (error) {
    console.error('创建知识库失败:', error)
    message.error('剧本知识库创建失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// ==================== AI Generation ====================
const handleAIGenerate = async () => {
  if (!aiInput.value.trim()) {
    message.warning('请输入剧本描述')
    return
  }

  isGenerating.value = true
  try {
    // 模拟AI生成过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    aiResult.value = `基于您的描述"${aiInput.value}"，AI为您生成了以下剧本大纲：\n\n【剧本标题】神秘的${aiInput.value}\n\n【背景设定】\n在一个充满悬疑的环境中，几位性格迥异的角色因为某种原因聚集在一起...\n\n【主要角色】\n1. 侦探 - 冷静理性，善于推理\n2. 嫌疑人A - 神秘莫测，行为可疑\n3. 嫌疑人B - 表面友善，内心复杂\n4. 证人 - 关键信息的持有者\n\n【剧情发展】\n第一幕：事件发生，角色登场\n第二幕：线索收集，推理分析\n第三幕：真相揭露，结局呈现\n\n【关键线索】\n- 线索1：现场遗留的神秘物品\n- 线索2：角色间的复杂关系\n- 线索3：时间线上的矛盾点\n\n这是一个充满悬念和推理乐趣的剧本框架，您可以基于此进行进一步的创作和完善。`
  } catch (error) {
    message.error('生成失败，请重试')
  } finally {
    isGenerating.value = false
  }
}

const clearAIResult = () => {
  aiResult.value = ''
  aiInput.value = ''
}

// 监听主题选择变化
watch(selectedTheme, (newValue) => {
  if (newValue) {
    const theme = recommendedThemes.value.find(t => t.value === newValue)
    if (theme) {
      aiInput.value = theme.label
      aiResult.value = `🎯 已选择推荐主题：\n\n【主题】${theme.label}\n\n【创作提示】\n这个主题为您提供了丰富的创作空间，您可以围绕这个主题展开想象，创造出独特的角色、情节和冲突。点击下方按钮，让AI帮您基于这个主题创作完整的剧本大纲。`
    }
  }
})

const switchToGenerateMode = () => {
  currentMode.value = 'generate'
}

const switchToDocumentMode = () => {
  currentMode.value = 'document'
}

const backToWelcome = () => {
  currentMode.value = 'welcome'
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  fileContent.value = ''
  scriptName.value = ''
  scriptDescription.value = ''
  scriptImage.value = null
  scriptImageUrl.value = ''
  aiInput.value = ''
  aiResult.value = ''
}
</script>

<template>
  <div :style="styles.layout">
    <!-- 主要内容区域 -->
    <div :style="styles.mainArea">
      <!-- 页面标题 -->
      <div class="px-4 py-3 border-b border-gray-200">
        <Title :level="2" class="text-blue-purple-600 m-0">
          剧本创作
        </Title>
        <Text type="secondary">选择创作方式，开始你的剧本创作之旅</Text>
      </div>

      <!-- 内容显示区域 -->
      <div :style="styles.contentArea">
        <!-- 欢迎页面 -->
        <div v-if="currentMode === 'welcome'" :style="styles.welcomeArea">
          <div class="mb-8">
            <Title :level="2" class="text-blue-purple-600 mb-2">
              开始你的创作之旅
            </Title>
            <Text type="secondary" class="text-lg">
              选择一个灵感启发方式，让创意自由流淌
            </Text>
          </div>

          <!-- 创作模式选择 -->
          <div class="mb-8">
            <div class="text-center mb-4">
              <Title :level="4" class="m-0">选择剧本创作方式</Title>
            </div>

            <Text type="secondary" class="block mb-6 text-center">选择你想要的创作方式，让创意自由流淌</Text>

            <div class="grid grid-cols-2 gap-6 max-w-3xl mx-auto">
              <Card
                 size="small"
                 hoverable
                 class="cursor-pointer text-center transition-all duration-200 border-gray-200"
                 @click="switchToGenerateMode"
               >
                <div class="py-6">
                  <BulbOutlined class="text-3xl mb-3 text-gray-400" />
                  <div>
                    <Text strong>一句话开始</Text>
                  </div>
                  <Text type="secondary" class="text-sm">输入一句话让AI帮你创作</Text>
                </div>
              </Card>

              <Card
                 size="small"
                 hoverable
                 class="cursor-pointer text-center transition-all duration-200 border-gray-200"
                 @click="switchToDocumentMode"
               >
                <div class="py-6">
                  <UploadOutlined class="text-3xl mb-3 text-gray-400" />
                  <div>
                    <Text strong>上传文档</Text>
                  </div>
                  <Text type="secondary" class="text-sm">上传已有文档作为剧本</Text>
                </div>
              </Card>
            </div>
          </div>
        </div>

        <!-- AI生成模式 -->
        <div v-else-if="currentMode === 'generate'" class="h-full flex flex-col">
          <div class="mb-4 flex items-center justify-between">
            <Title :level="3" class="text-blue-purple-600 m-0">
              <BulbOutlined class="mr-2" />
              一句话开始创作
            </Title>
            <Button @click="backToWelcome">返回</Button>
          </div>

          <div class="flex-1 flex flex-col">
            <!-- 推荐主题选择 -->
            <div class="mb-6">
              <Text strong class="block mb-2">推荐主题（可选）</Text>
              <Select
                v-model:value="selectedTheme"
                placeholder="选择一个推荐主题，或直接在下方输入自定义描述"
                allow-clear
                class="w-full"
              >
                <Select.Option v-for="theme in recommendedThemes" :key="theme.value" :value="theme.value">
                  {{ theme.label }}
                </Select.Option>
              </Select>
            </div>

            <!-- AI结果显示 -->
            <div v-if="aiResult" class="flex-1 mb-4">
              <div class="flex items-center justify-between mb-2">
                <Text strong>生成结果</Text>
                <Button size="small" @click="clearAIResult">清空</Button>
              </div>
              <div class="p-4 bg-gray-50 rounded-lg h-full overflow-y-auto">
                <Paragraph class="whitespace-pre-wrap text-sm m-0">
                  {{ aiResult }}
                </Paragraph>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="flex-1 flex items-center justify-center">
              <div class="text-center">
                <div class="text-6xl mb-4">✨</div>
                <Title :level="4" class="mb-2">准备开始创作</Title>
                <Text type="secondary">在下方输入您的创意描述，让AI帮您生成精彩的剧本</Text>
              </div>
            </div>
          </div>
        </div>

        <!-- 文档上传模式 -->
        <div v-else-if="currentMode === 'document'" class="h-full flex flex-col">
          <div class="mb-4 flex items-center justify-between">
            <Title :level="3" class="text-blue-purple-600 m-0">
              <UploadOutlined class="mr-2" />
              上传文档
            </Title>
            <Button @click="backToWelcome">返回</Button>
          </div>

          <div class="flex-1 flex flex-col">
            <!-- 剧本信息表单 -->
            <div class="max-w-md mx-auto mb-6 space-y-4">
              <!-- 剧本名称 -->
              <div>
                <Text strong class="block mb-2">剧本名称 <Text type="danger">*</Text></Text>
                <Input
                  v-model:value="scriptName"
                  placeholder="请输入剧本名称"
                  size="large"
                />
              </div>

              <!-- 剧本描述 -->
              <div>
                <Text strong class="block mb-2">剧本描述 <Text type="secondary">(可选)</Text></Text>
                <Input.TextArea
                  v-model:value="scriptDescription"
                  placeholder="请简要描述剧本的主要内容、背景或特色..."
                  :rows="3"
                  show-count
                  :maxlength="500"
                />
              </div>

              <!-- 剧本图片 -->
              <div>
                <Text strong class="block mb-2">剧本封面图片 <Text type="secondary">(可选)</Text></Text>
                <div v-if="!scriptImage" class="border-2 border-dashed border-gray-300 rounded-lg p-3 max-w-[200px] mx-auto">
                  <Upload
                    :custom-request="handleImageUpload"
                    :before-upload="beforeImageUpload"
                    :show-upload-list="false"
                    accept="image/*"
                    class="w-full"
                  >
                    <div class="flex flex-col items-center justify-center py-3 min-h-[120px]">
                      <div class="text-xl mb-2">🖼️</div>
                      <Text type="secondary" class="text-sm">点击上传图片</Text>
                      <div class="mt-1">
                        <Text type="secondary" class="text-xs">支持 JPG、PNG、GIF 格式，大小不超过 1MB</Text>
                      </div>
                    </div>
                  </Upload>
                </div>

                <div v-else class="border border-gray-300 rounded-lg p-3">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <div class="text-lg mr-2">🖼️</div>
                      <div>
                        <Text strong>{{ scriptImage.name }}</Text>
                        <div>
                          <Text type="secondary" class="text-sm">({{ (scriptImage.size / 1024).toFixed(1) }} KB)</Text>
                        </div>
                      </div>
                    </div>
                    <Button size="small" @click="removeImage">移除</Button>
                  </div>
                </div>
              </div>
                  <!-- 文件上传区域 -->
            <div v-if="!uploadedFile" class="flex-1 flex items-center justify-center">
              <div class="text-center max-w-md">
                <div class="text-6xl mb-4">📄</div>
                <Title :level="4" class="mb-4">上传剧本文档</Title>
                <Text type="secondary" class="block mb-6">
                  支持上传 .txt、.pdf、.doc、.docx 格式的文件，文件大小不超过 1MB
                </Text>

                <Upload
                  :custom-request="handleFileUpload"
                  :before-upload="beforeUpload"
                  :show-upload-list="false"
                  accept=".txt,.pdf,.doc,.docx"
                >
                  <Button type="primary" size="large">
                    <template #icon>
                      <UploadOutlined />
                    </template>
                    选择文件上传
                  </Button>
                </Upload>

              </div>
            </div>

            <!-- 文件上传成功区域 -->
            <div v-else class="flex-1 flex flex-col items-center justify-center">
              <div class="text-center max-w-md">
                <div class="text-6xl mb-4">✅</div>
                <Title :level="4" class="mb-4">文件上传成功</Title>

                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                  <div class="flex items-center justify-center mb-2">
                    <FileTextOutlined class="text-blue-purple-500 mr-2" />
                    <Text strong>{{ uploadedFile.name }}</Text>
                  </div>
                  <Text type="secondary">({{ (uploadedFile.size / 1024).toFixed(1) }} KB)</Text>
                </div>

                <div class="space-y-3">
                   <Button size="large" block @click="removeFile" :disabled="isSubmitting">
                     重新选择文件
                   </Button>
                 </div>
              </div>
            </div>
              <!-- 表单提交按钮 -->
              <div class="pt-4">
                <Button
                  type="primary"
                  size="large"
                  block
                  :loading="isSubmitting"
                  :disabled="!scriptName.trim() || !uploadedFile || isSubmitting"
                  @click="handleSubmit"
                  class="glass-button"
                >
                  {{ isSubmitting ? '创建中...' : '创建剧本' }}
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div v-if="currentMode === 'generate'" :style="styles.inputArea">
        <div class="mb-4">
          <Text strong class="block mb-2">剧本描述</Text>
          <Input.TextArea
            v-model:value="aiInput"
            placeholder="请描述您想要的剧本类型、背景、角色等信息...\n例如：一个发生在古代宫廷的悬疑剧本，涉及权力斗争和爱情纠葛"
            :rows="3"
            :disabled="isGenerating"
          />
        </div>

        <Button
          type="primary"
          size="large"
          block
          :loading="isGenerating"
          :disabled="!aiInput.trim()"
          @click="handleAIGenerate"
        >
          <template #icon>
            <SendOutlined />
          </template>
          {{ isGenerating ? '生成中...' : '生成剧本' }}
        </Button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.text-blue-purple-300 {
  color: var(--blue-purple-300);
}

.text-blue-purple-400 {
  color: var(--blue-purple-400);
}

.text-blue-purple-500 {
  color: var(--blue-purple-500);
}

.text-blue-purple-600 {
  color: var(--blue-purple-600);
}

.border-blue-purple-200 {
  border-color: #e0e7ff;
}

.bg-blue-purple-50 {
  background-color: #f8faff;
}

.bg-blue-purple-100 {
  background-color: #f0f4ff;
}

.bg-blue-purple-500 {
  background-color: #6366f1;
}

/* 玻璃效果按钮样式 */
.glass-button {
  background: rgba(99, 102, 241, 0.15) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(99, 102, 241, 0.3) !important;
  color: #6366f1 !important;
  transition: all 0.3s ease !important;
}

.glass-button:hover {
  background: rgba(99, 102, 241, 0.25) !important;
  border-color: rgba(99, 102, 241, 0.5) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2) !important;
}

.glass-button:active {
  transform: translateY(0) !important;
}

.glass-button.ant-btn-loading {
  background: rgba(99, 102, 241, 0.1) !important;
}

/* 右侧面板滚动条样式 */
.ant-card {
  border-radius: 8px;
}

.ant-card-small > .ant-card-head {
  padding: 8px 12px;
  min-height: auto;
}

.ant-card-small > .ant-card-body {
  padding: 12px;
}
</style>
